import requests
import sys
import akshare as ak
from wxpusher import WxPusher
import pymysql
from redis_client import StockRedisClient

stock_data = {} 
# MySQL database configuration
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': 'Zhj1030222323@',
    'database': 'mydb'
}
client = StockRedisClient(password="Zhj1030222323@")

def parse_json(path):
    import json

    with open(path, "r", encoding="utf-8") as f:
        data = json.load(f)
    user_list = data.get("user", [])
    result = []
    for user in user_list:
        print(user)
        name = user.get("name")
        uid = user.get("wxpusher_uid")
        token = user.get("wxpusher_token")
        result.append(
            {
                "username": name,
                "uid": uid,
                "token": token,
            })
    return result



def notify_user(wx_uid, wx_token, msg, content_type, summary):
    response = WxPusher.send_message(
        msg, uids=wx_uid, content_type=content_type, token=wx_token, summary=summary)
    print(response)

# Function to fetch stock data from MySQL using pymysql
def fetch_stock_data():
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT stock_name, stock_code, highest_price, lowest_price , reason FROM check_prices")
            stocks = cursor.fetchall()
    finally:
        connection.close()

    return stocks

# Function to get current stock price using akshare
def get_current_price(stock_code):
    global stock_data
    if len(stock_data) == 0:
        stock_data = ak.stock_zh_a_spot_em()
    current_price = stock_data[stock_data['代码'] == stock_code]['最新价'].values[0]
    return current_price


# Function to send notification via wxchatpusher
def send_notification(config, stock_name, stock_code, current_price, lowest_price , highest_price , reason ):
    global client
    message = f"Alert: {stock_name} ({stock_code}) current price: {current_price} is out of bounds (min: {lowest_price }, max: {highest_price } reason : {reason})"
    if client.is_stock_time_valid(stock_code) :
        return
    for item in config:
        notify_user(wx_uid=[item["uid"]], wx_token=item["token"], msg=message, content_type=1,summary="Stock Price Alert")
        client.set_stock_now(stock_code, 12 * 3600)


# Main function
def main():
    config = parse_json(sys.argv[1])
    stocks = fetch_stock_data()
    for stock in stocks:
        stock_name, stock_code, highest_price , lowest_price, reason  = stock
        current_price = get_current_price(stock_code)
        if current_price < lowest_price  or current_price > highest_price :
            print("send noti to every one")
            send_notification(config, stock_name, stock_code, current_price, lowest_price , highest_price, reason)

if __name__ == "__main__":
    main()
